package poswar.contribute.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import poswar.contribute.exception.QuestionWhereAnsweredException;
import poswar.contribute.util.FriendModeManager;


public class Question implements Serializable {
	private static final long serialVersionUID = 1L;
	
	private String text;
	private HashMap<String, Answer> answers = new HashMap<String, Answer>();	
	
	public static Question build(String text) {
		Question question = new Question();
		
		question.text = text;
		
		return question;
	}

	public String getText() {
		return text;
	}
	
	public void setText(String text) {
		FriendModeManager.assertFriendAccess();
		this.text = text;
	}

	public void publishAnswer(Answer answer) throws QuestionWhereAnsweredException {
		if (answers.containsKey(answer.getEmail())) {
			throw new QuestionWhereAnsweredException();
		} else {
			answers.put(answer.getEmail(), answer);
		}
	}
	
	public HashMap<String, Answer> getAnswers() {
		return answers;
	}
	
	public int getNumOfAnswered() {
		return answers.size();
	}
	
	public List<Answer> getAnswerList() {
		ArrayList<Answer> copy = new ArrayList<Answer>();
		copy.addAll(answers.values());
		
		Collections.sort(copy, new Comparator<Answer>() {
			public int compare(Answer a1, Answer a2) {
				// Descending size order
				return a2.getText().length()-a1.getText().length();
			}
		});
		return copy;		
	}
}
